<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>

          <a-col :span="24">
            <a-form-model-item label="分组" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="unitCode">
              <a-select style="width: 180px; margin-left:20px" placeholder="请选择" @change="setGroupIdAndName"  optionFilterProp="label" showSearch allowClear>
                <a-select-option v-for="item in unitGroupList" :key="item.id" :label="item.unitCode" :value="item.id">{{item.groupName}}</a-select-option>
              </a-select>  
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="unitName">
              <a-input style="width: 180px; margin-left:20px" v-model="model.unitCode" placeholder="请输入单位名称" @change="unitCodeChange"   ></a-input>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="parentId">
              <div style="margin-top:20px;margin-bottom: 20px; font-weight: bold; font-size: 20px">
                单位换算
              </div>

          <div v-for="(item,SourceIndex) in forwardList" :key="SourceIndex"  style= " background-color: #ffffff;margin-bottom: 20px;">

            <div style="display:flex">
              <div v-if="model.unitCode == null || model.unitCode == ''" style="min-width: 40px;" >
                  1 - =
                </div>
                
                <div v-else style="min-width: 60px;" >
                  1 {{model.unitCode}} =
                </div> 
              
              <a-input v-model="item.value"  placeholder="转换值" style="width: 180px; margin-left:10px" @change="setConvertValue(item,SourceIndex)"  ></a-input>

              <a-select style="min-width: 100px; ;width: 180px; margin-left:20px" placeholder="请选择" @change="setTargetUnitAndId($event,item,SourceIndex)"   optionFilterProp="label" showSearch allowClear>
                <a-select-option v-for="UnitItem in unitList" :key="UnitItem.id" :label="UnitItem.unitCode" :value="UnitItem.id">{{UnitItem.unitCode}}</a-select-option>
              </a-select>

              <a-button style="margin-left:30px" @click="handleDelete(SourceIndex)" type="primary">删除</a-button>
            </div>

              <!-- 转换对象一组一组展示的效果 -->
              <!-- 由于正向转换对象和反向转换对象下标是对应的，所有可以通过相同下标来进行成组展示的效果 -->
              <div style="margin-bottom:20px">

                <span  v-if="contraryList[SourceIndex].sourceUnit == null || contraryList[SourceIndex].sourceUnit == ''">
                  1 - =
                </span>

                <span v-else style="width:200px">
                1 {{contraryList[SourceIndex].sourceUnit}} =
                </span>

                <a-input v-model="contraryList[SourceIndex].value"  placeholder="转换值" style="width: 180px; margin-left:5px"></a-input>

                <span v-if="contraryList[SourceIndex].targetUnit == null || contraryList[SourceIndex].targetUnit == ''">
                  1 - 
                </span>

                <span v-else>
                {{contraryList[SourceIndex].targetUnit}} 
                </span>
              </div>

          </div>

          <!-- 转换对象分开展示的效果 -->

          <!-- <div v-for="(contraryItem,index) in contraryList" >

            <div style="margin-bottom:20px">

                <span  v-if="contraryItem.sourceUnit == null || contraryItem.sourceUnit == ''">
                  1 - =
                </span>

                <span v-else style="width:200px">
                1 {{contraryItem.sourceUnit}} =
                </span>

              <a-input v-model="contraryItem.value"  placeholder="转换值" style="width: 180px; margin-left:5px"></a-input>

              <span v-if="contraryItem.targetUnit == null || contraryItem.targetUnit == ''">
                  1 - 
                </span>

              <span v-else>
                {{contraryItem.targetUnit}} 
              </span>
            </div>
          </div> -->

    <div style="color:blue;cursor: pointer;" @click="addRow()"  >
        添加单位换算
    </div>


            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'

  export default {
    name: 'CyEmissionUnitForm',
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        model:{
          parentName:'',
          parentId:'',
          unitConvertList:[],
         },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
        },
        url: {
          add: "/emission/factor/cyEmissionUnit/add",
          edit: "/emission/factor/cyEmissionUnit/edit",
          queryById: "/CyEmissionUnit/cyEmissionUnit/queryById",
          unitGroup:"/CyFactorUnitGroup/cyFactorUnitGroup/list",
          unitList: "/emission/factor/cyEmissionUnit/list",
        },
        contraryList:[],
        forwardList:[],
        unitGroupList:[],
        unitList:[],
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      this.searchGroup();
      this.searchUnit();
    },
    methods: {
      setGroupIdAndName(selectedObj){
        let theIndex =  this.unitGroupList.findIndex(ele=>ele.id == selectedObj)
        let theObj = this.unitGroupList[theIndex];
        this.model.parentName =  theObj.groupName
        this.model.parentId =  theObj.id
        console.log(this.model)
      },
      setTargetUnitAndId(selectedObj,item,SourceIndex){
        let theIndex =  this.unitList.findIndex(ele=>ele.id == selectedObj)
        let theObj = this.unitList[theIndex];

        item.sourceUnit = this.model.unitCode;
        item.targetUnit = theObj.unitCode;
        item.targetUnitId = theObj.id;

        console.log(item);

        
        this.contraryList[SourceIndex].sourceUnit = item.targetUnit;
        this.contraryList[SourceIndex].unitId = item.targetUnitId;
        this.contraryList[SourceIndex].targetUnit = item.sourceUnit;

        
      },
      //正向单位转换对象中的转换值改变时，同时改变反向转换对象中的转换值（自动设置为正向的倒数）
      setConvertValue(item,SourceIndex){
        console.log(item.value)
        if(item.value!=null && item.value!=undefined && item.value!= 0){
          this.contraryList[SourceIndex].value = (1/item.value).toFixed(6)
        }
      },
      // 主体中的单位值改变时，同时改变反向转换对象中的目标单位
      unitCodeChange(e){
        console.log(this.model.unitCode)
        if(this.contraryList!=null && this.contraryList.length>0){
          for(let i=0;i<this.contraryList.length;i++){
            this.contraryList[i].targetUnit = this.model.unitCode
          }
        }
      },
      addRow(){
        this.forwardList.push({sourceUnit:'',sourceUnitId:'',value:'',targetUnit:'',targetUnitId:'',type:"1"});
        // this.model.unitConvertList.push({sourceUnit:'',sourceUnitId:'',value:'',targetUnit:'',targetUnitId:'',type:"1"});
        this.contraryList.push({sourceUnit: '',unitId:'',value:'',targetUnit:'',targetUnitId:'',type:"2"})

        console.log(this.modelDefault)
      },
      //删除转换对象
      handleDelete(SourceIndex){
            this.forwardList.splice(SourceIndex,1)
            this.contraryList.splice(SourceIndex,1)
      },
      //单位分组分页列表查询
      searchGroup(){
        getAction(this.url.unitGroup).then(res=>{
          this.unitGroupList = res.result.records
      })
      },
      //查询单位
      searchUnit(){
        getAction(this.url.unitList).then(res=>{
          this.unitList = res.result.records
      }) 
      },
      add () {
        this.edit(this.modelDefault);
        
      },
      edit (record) {
        this.model = Object.assign({}, record);
        this.visible = true;
      },
      submitForm () {

        if(this.model.parentName == null || this.model.parentName == '' || this.model.parentName == undefined){
          this.$message.warn('请选择单位分组')
        }else{
          if(this.model.unitCode == null || this.model.unitCode == '' || this.model.unitCode == undefined){
            this.$message.warn('请输入单位')
          }else{

        if(this.model.unitConvertList == undefined){
          this.model.unitConvertList = [];
        }

        for(let i=0;i<this.contraryList.length;i++){
          this.model.unitConvertList.push(this.contraryList[i]);
        }

        for(let i=0;i<this.forwardList.length;i++){
          this.model.unitConvertList.push(this.forwardList[i]);
        }
        console.log(this.model);
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
         
        })
          }
        }
      },
    }
  }
</script>